# -*- coding: UTF-8 -*-

from decimal import Decimal

from dtrader.strategy import LiveTradeStrategy
from dtrader.price_handler.tushare_test_tick import TushareTestTickPriceHandler
from dtrader.broker.mailbroker import MailBroker
try:
    import Queue as queue
except ImportError:
    import queue

class SimpleStrategy(LiveTradeStrategy):

    def __init__(self):

        #初始化pricehandler
        events_queue = queue.Queue()
        tikcers = ['600479']
        price_handler = TushareTestTickPriceHandler(events_queue,tikcers,'2017-06-01')

        #初始化broker
        broker = MailBroker(['690484812@qq.com','hezhenke123@163.com'],events_queue)
        super(SimpleStrategy, self).__init__(price_handler,broker)


        self.keyword = "SimpleStrategy"
        self.__option = {
            "600479":{"buy_price":15,"sell_price":17,"buy_amount":"1000","sell_amount":"1000"}
        }



    def on_tick(self, event):
        try:
            ticker = event.ticker
            bid = event.bid
            ask = event.ask
            if not self.__option.has_key(ticker):
                return
            portfolio = self.get_portfolio()
            if self.__option[ticker].has_key('buy_price') and self.__option[ticker]['buy_price'] is not None:
                buy_price = Decimal(str(self.__option[ticker]['buy_price']))
                buy_amount = Decimal(str(self.__option[ticker]['buy_amount']))
                if buy_price >= bid and buy_amount >= 100:
                    if not portfolio.positions.has_key(ticker):
                        #发送买入信号
                        self.create_limit_order(ticker,"BOT",buy_amount,bid)
                        self.get_logger().info("buy ticker:%s,amount:%s,price:%s"%(ticker,buy_amount,bid))
            if self.__option[ticker].has_key('sell_price') and self.__option[ticker]['sell_price'] is not None:
                sell_price = Decimal(str(self.__option[ticker]['sell_price']))
                sell_amount = Decimal(str(self.__option[ticker]['sell_amount']))
                if sell_price <= ask and sell_amount > 100:
                    #发出卖出信号
                    if portfolio.portfolio.positions.has_key(ticker):
                        self.create_limit_order(ticker, "SLD", sell_amount, ask)
                        self.get_logger().info("sell ticker:%s,amount:%s,price:%s"%(ticker,sell_amount,ask))


        except Exception,e:
            self.get_logger().error("on_tick error,message:%s" % (e.message))



    def get_tickers(self):
        return self.__option.keys()

    def on_bar(self,event):
        pass

if __name__ == "__main__":
    strategy = SimpleStrategy()
    strategy.run();
